<?php

namespace iBrand\Component\Order\Models;

use iBrand\Shop\Core\Models\OrderRefundRelation;
use iBrand\Shop\Core\Models\RefundItem;
use Illuminate\Database\Eloquent\Model;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;
use Illuminate\Database\Eloquent\SoftDeletes;

class OrderItem extends Model implements Transformable
{
    use SoftDeletes;
    use TransformableTrait;

    protected $table = 'el_order_item';

    protected $guarded = ['id'];

    protected $appends = ['is_refunded', 'item_sku',
        'item_category', 'units_total_yuan', 'total_yuan', 'redeem_point'];

    protected $model;

    public function units()
    {
        return $this->hasMany(OrderItemUnit::class);
    }

    public function order()
    {
        return $this->belongsTo(Order::class);
    }

    public function refundItems()
    {
        return $this->hasMany(RefundItem::class, 'order_item_id');
    }

    public function getModel()
    {
        if ($this->model) {
            return $this->model;
        }

        $model = $this->type;
        $model = new $model();
        $this->model = $model->find($this->item_id);

        return $this->model;
    }

    public function getItemKey($type = 'sku')
    {
        return $this->getModel()->getKeyCode($type);
    }

    public function getItemId()
    {
        return $this->getModel()->getDetailIdAttribute();
    }

    public function getFactoryPrice()
    {
        return $this->getModel()->getFactoryPriceAttribute();
    }

    public function getTotal()
    {
        return $this->total;
    }

    public function setUnitPriceAttribute($value)
    {
        $this->attributes['unit_price'] = $value * 100;
        $this->recalculateUnitsTotal();
    }

    /**
     *  Recalculates total after units total or adjustments total change.
     */
    public function recalculateTotal()
    {
        $this->total = $this->units_total + $this->adjustments_total;

        if ($this->total < 0) {
            $this->total = 0;
        }

        if (null !== $this->order) {
            $this->order->recalculateItemsTotal();
        }
    }

    public function recalculateAdjustmentsTotal()
    {
        $this->adjustments_total = $this->divide_order_discount + $this->item_discount;

        $this->recalculateTotal();
    }

    public function recalculateUnitsTotal()
    {
        $this->units_total = $this->quantity * $this->unit_price;

        $this->recalculateTotal();
    }

    public function setItemMetaAttribute($value)
    {
        $this->attributes['item_meta'] = json_encode($value);
    }

    public function getItemMetaAttribute($value)
    {
        return json_decode($value, true);
    }

    public function getIsRefundedAttribute()
    {
        if (!$this->order) return false;

        $refund = $this->refundItems->filter(function ($refund) {
            return $refund->refund->status == 1;
        })->first();

        if ($refund) {
            return true;
        }

        /*如果是换货订单*/
        if (OrderRefundRelation::where('order_id', $this->order->id)->first()) {
            return true;
        }

        return false;
    }

    public function getItemSkuAttribute()
    {
        /*if ($model = $this->getModel()) {
            if ($this->type == 'iBrand\\Component\\Product\\Models\\Product') {
                return $this->getItemKey();
            } elseif ($this->type == 'iBrand\\Component\\Product\\Models\\Goods') {
                return $model->goods_no;
            }
        }*/

        if ($model = $this->getModel()) {
            if ($this->type == 'iBrand\\Component\\Goods\\Models\\GoodsProduct') {
                return $model->goods->goods_no;
            } elseif ($this->type == 'iBrand\\Component\\Goods\\Models\\Goods') {
                return $model->goods_no;
            }
        }

        return null;
    }

    public function getItemCategoryAttribute()
    {
        /*if ($model = $this->getModel() AND $goods = Goods::find($this->getItemKey('spu'))) {
            return $goods->getCategories()->pluck('name');
        }*/
        return null;
    }

    /**
     * 判断这个订单商品是否能够获得积分
     *
     * @param $pointInvalidRatio  判断积分有效费率
     *
     * @return bool
     */
    public function isCanGetPoint($pointInvalidRatio)
    {
        return $this->units_total > 0
            AND ($this->total / $this->quantity) >= ($this->getModel()->market_price * $pointInvalidRatio);
    }

    /**
     * 获取到这个订单能够正常获取到的积分
     */
    public function getPoint()
    {
        /*$itemId = $this->getItemId();

        $pointGoods = PointGoods::ofItem($itemId)->first();

        if ($pointGoods AND $pointGoods->value != 0 AND $pointGoods->status == 1) {

            return $pointGoods->getPoint($this->total, $this->quantity);
        }*/

        if (settings('shop_get_point')) {
            return $this->total / 100;
        }

        return 0;
    }

    public function getUnitsTotalYuanAttribute()
    {
        return number_format($this->units_total / 100, 2, ".", "");
    }

    public function getTotalYuanAttribute()
    {
        return number_format($this->total / 100, 2, ".", "");
    }

    public function getRedeemPointAttribute()
    {
        if ($model = $this->getModel()) {
            return $model->redeem_point;
        }

        return 0;
    }

}
